<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\stat;

use app\model\QqMaterialDailyReportExtModel;
use app\model\QqMaterialDailyReportModel;
use app\model\QqVideoModel;
use app\service\BaseService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class QqVideoStatService extends BaseService implements StatModelInterface
{
    /**
     * 获取素材消耗信息.
     * @param string $advertiserId 账户ID
     * @param int $statDate 日期
     * @param array $params 表参数
     * @return null|array|false|mixed|Model|QqMaterialDailyReportModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getStatInfo(string $advertiserId = '', int $statDate = 0, array $params = [])
    {
        if (empty($params['material_id'])) {
            return false;
        }
        $statDate = date('Ymd', strtotime($params['date']));
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['stat_date', '=', $statDate],
            ['video_id', '=', $params['material_id']],
        ];
        return (new QqMaterialDailyReportModel())->where($where)->find();
    }

    /**
     * 修改报表信息.
     * @param Model $model 数据模型
     * @param array $params 表参数
     */
    public static function updateStatData(Model $model, array $params = []): bool
    {
        if (! $model instanceof QqMaterialDailyReportModel) {
            return self::setError('报表模型错误');
        }
        try {
            // 主表
            $data = [
                'cost' => $params['cost'],
                'update_time' => time(),
            ];
            $model->setAttrs($data);
            $model->save();
            // 附表
            $extData = [
                'content' => json_encode($params, JSON_UNESCAPED_UNICODE),
                'update_time' => time(),
            ];
            (new QqMaterialDailyReportExtModel())->where('report_id', $model->getKey())->update($extData);
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 插入报表信息.
     * @param string $advertiserId 账户id
     * @param array $params 表参数
     */
    public static function insertStatData(string $advertiserId = '', array $params = []): bool
    {
        // 过滤无媒体id的数据
        if (! isset($params['material_id'])) {
            return true;
        }
        try {
            $accountInfo = BaseService::getClientAccountInfo($advertiserId);
            // 主表
            $data = [
                'company_id' => $accountInfo['company_id'],
                'client_id' => $accountInfo['client_id'],
                'account_id' => $accountInfo['id'],
                'advertiser_id' => $advertiserId,
                'stat_date' => date('Ymd', strtotime($params['date'])),
                'video_id' => $params['material_id'],
                'signature' => self::getVideoSignature($advertiserId, $params['material_id']),
                'cost' => $params['cost'],
                'create_time' => time(),
            ];
            $model = new QqMaterialDailyReportModel();
            $id = $model->insertGetId($data);
            // 附表
            $extData = [
                'company_id' => $accountInfo['company_id'],
                'client_id' => $accountInfo['client_id'],
                'account_id' => $accountInfo['id'],
                'report_id' => $id,
                'advertiser_id' => $advertiserId,
                'stat_date' => date('Ymd', strtotime($params['date'])),
                'content' => json_encode($params, JSON_UNESCAPED_UNICODE),
                'create_time' => time(),
            ];
            (new QqMaterialDailyReportExtModel())->insert($extData);
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 对比数据是否相同.
     * @param Model $model 模型
     * @param array $param 表参数
     */
    public static function isSame(Model $model, array $param = []): bool
    {
        $difField = [
            'cost',
        ];
        // 验证数据是否相同
        foreach ($difField as $val) {
            if ($model->getAttr($val) != $param[$val]) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取素材signature.
     * @param string $advertiserId 账户id
     * @param string $videoId 视频id
     * @return mixed
     */
    private static function getVideoSignature(string $advertiserId = '', string $videoId = '')
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['video_id', '=', $videoId],
        ];
        return (new QqVideoModel())->where($where)->value('signature') ?? '';
    }
}
